package recusive;

/**
 * @author luo
 * @description
 * @since 2022/7/20 13:25
 */
public class AddTwoNumbers {


    public static void main(String[] args) {
        ListNode l1 = new ListNode(9);
        ListNode left = l1;
        for (int i = 0; i < 6; i++) {
            left.next = new ListNode(9);
            left = left.next;
        }
        ListNode l2 = new ListNode(9);
        ListNode right = l2;
        for (int i = 0; i < 3; i++) {
            right.next = new ListNode(9);
            right = right.next;
        }
        ListNode listNode = new AddTwoNumbers().addTwoNumbers(l1, l2);
        while (listNode != null) {
            System.out.print(listNode.val + "\t");
            listNode = listNode.next;
        }
//        期望结果:[8,9,9,9,0,0,0,1]
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {


        return add(l1, l2, 0);

    }

    /**
     * @param l1
     * @param l2
     * @param carry 进位
     * @return
     */
    private ListNode add(ListNode l1, ListNode l2, int carry) {

        int l1Value = 0;
        int l2Value = 0;

        if (l1 != null) {
            l1Value = l1.val;
        }
        if (l2 != null) {
            l2Value = l2.val;
        }

        ListNode result = new ListNode();
        int sum = l1Value + l2Value;
        result.val = (sum + carry) % 10;
        // 新的进位
        int newCarry = (sum + carry) / 10;
        if (l1 != null && l2 != null) {
            result.next = add(l1.next, l2.next, newCarry);
        } else if ((l1 == null && l2 == null)) {
            if (carry == 0 && newCarry == 0) {

                return null;
            }
            result.next = add(null, null, newCarry);
        } else if (l1 != null) {
            result.next = add(l1.next, null, newCarry);
        } else /*if (l2 != null)*/ {
            result.next = add(null, l2.next, newCarry);
        }


        return result;
    }
}
